const orderModel = require("../modules/orderModel");

const db = {};
db.query = async body => {
    console.log("查询订单...");
    let { query, limit, skip, filter } = body;
    if (query == null) query = {};
    if (filter == null) filter = {};
    try {
        let result = await orderModel
            .find(query)
            .populate([{ path: "user_id" }, { path: "goods_id", populate: { path: "classifyId", select: "name" } }])
            .skip(skip)
            .limit(limit);
        let sum = await orderModel.find(query).count();

        //筛选数据
        if (filter.order_id != null && filter.order_id != "") {
            result = result.filter(item => {
                return filter.order_id == item._id;
            });
        } else {
            if (filter.class != null && filter.class != "") {
                result = result.filter(item => {
                    return filter.class == item.goods_id.classId.name;
                });
            }
            if (filter.date != null && filter.date != "") {
                result = result.filter(item => {
                    return new Date(item.date).getTime() >= new Date(filter.date[0]).getTime() && new Date(item.date).getTime() <= new Date(filter.date[1]);
                });
            }
        }
        return {
            code: 1,
            sum,
            result
        };
    } catch (error) {
        console.log(error);
        return {
            code: 0,
            message: "查询订单失败"
        };
    }
};
db.create = async body => {
    console.log("创建订单...");
    try {
        let result = await orderModel.create(body);
        return {
            code: 1,
            result
        };
    } catch (error) {
        return {
            code: 0,
            message: "创建订单失败"
        };
    }
};

db.update = async body => {
    console.log("修改订单...");
    try {
        const { _id, data } = body;
        let result = await orderModel.updateOne({ _id }, data);
        return {
            code: 1,
            result
        };
    } catch (error) {
        return {
            code: 0,
            message: "数据修改失败"
        };
    }
};
module.exports = db;
